package com.qw.qrweb.controller;

import com.qw.qrweb.model.api.ApiResponse;
import com.qw.qrweb.service.SettingService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
public class SettingController {

    @Resource
    SettingService settingService;

    @GetMapping("/api/get-title")
    public String getTitle() {
        return ApiResponse.ok(settingService.getTtile());
    }

    @PostMapping("/api/set-title")
    public String setTitle(@RequestParam("title") String title) {
        return ApiResponse.ok(settingService.updateTtile(title));
    }

    @PostMapping("/api/upload-music")
    public String uploadMusic(@RequestParam("music") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ApiResponse.intError();
            }

            Path path = Paths.get("/web/images/uploads/");
            // 保存文件到服务器
            Files.copy(file.getInputStream(), path.resolve("new-music.mp3"), StandardCopyOption.REPLACE_EXISTING);


            // 返回响应
            return ApiResponse.ok("背景音乐设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return ApiResponse.sysError();
        }
    }

    @PostMapping("/api/set-music")
    public String setMusic() {
        Path path = Paths.get("/web/images/uploads/");
        try {
            Path source = path.resolve("new-music.mp3");
            Path target = path.resolve("anywhere.mp3");

            // 确保新的音乐文件存在
            if (!Files.exists(source)) {
                return ApiResponse.intError();
            }

            Files.copy(source, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);

            return ApiResponse.ok("背景音乐更新成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResponse.sysError();
        }
    }

}
